<!--首页-访问量分布详情页面-->
<template>
	<div class="app-container">
		<el-row type="flex" :gutter="10" justify="space-between">
			<el-col :xs="12" :sm="12" :md="12" :lg="12">
				<div ref="mapRef" class="bg-map" :style="{ height: height, width: width }"></div>
			</el-col>
			<el-col :span="12">
				<div class="table-background-color">
					<el-table id="table" v-loading="loading" class="el-table-title-no" max-height="800" :data="tableData" stripe @sort-change="sorable">
						<el-table-column prop="areaName" label="归属地区" width="80" :show-overflow-tooltip="true"></el-table-column>
						<el-table-column prop="visitCount" label="访问量" sortable="'custom'" :show-overflow-tooltip="true">
							<template #default="scope">
								<a style="border-bottom: solid 1px #ccc; line-height: 0.9" @click="handleRouterBusinessOverview(scope.row)">{{
									scope.row.visitCount
								}}</a>
								<svg-icon :icon-class="rowIcon(scope.row.visitCount, scope.row.avgVisitCount)" class="icon-class" />
								<span :style="rowSpanClass(scope.row.visitCount, scope.row.avgVisitCount)">{{
									rowRate(scope.row.visitCount, scope.row.avgVisitCount)
								}}</span>
							</template>
						</el-table-column>
						<el-table-column prop="avgHandleLen" label="平均响应时长" sortable="'custom'" :show-overflow-tooltip="true">
							<template #default="scope">
								<a>{{ toDecimalFormat(scope.row.avgHandleLen) }}</a>
								<svg-icon :icon-class="rowIcon(scope.row.avgHandleLen, scope.row.avgAvgRespTime)" class="icon-class" />
								<span :style="rowSpanClass(scope.row.avgHandleLen, scope.row.avgAvgRespTime)">{{
									rowRate(scope.row.avgHandleLen, scope.row.avgAvgRespTime)
								}}</span>
							</template>
						</el-table-column>
						<el-table-column prop="failVisitCount" label="失败访问量" sortable="'custom'" :show-overflow-tooltip="true">
							<template #default="scope">
								<a style="border-bottom: solid 1px #ccc; line-height: 0.9" @click="handleRouterBusinessOverview(scope.row)">{{
									scope.row.failVisitCount
								}}</a>
								<svg-icon :icon-class="rowIcon(scope.row.failVisitCount, scope.row.avgFailVisitCount)" class="icon-class" />
								<span :style="rowSpanClass(scope.row.failVisitCount, scope.row.avgFailVisitCount)">{{
									rowRate(scope.row.failVisitCount, scope.row.avgFailVisitCount)
								}}</span>
							</template>
						</el-table-column>
						<el-table-column prop="visitAlarmCount" label="告警访问量" sortable="'custom'" :show-overflow-tooltip="true">
							<template #default="scope">
								<a style="border-bottom: solid 1px #ccc; line-height: 0.9" @click="handleRouterBusinessOverview(scope.row)">{{
									scope.row.visitAlarmCount
								}}</a>
								<svg-icon :icon-class="rowIcon(scope.row.visitAlarmCount, scope.row.avgVisitAlarmCount)" class="icon-class" />
								<span :style="rowSpanClass(scope.row.visitAlarmCount, scope.row.avgVisitAlarmCount)">{{
									rowRate(scope.row.visitAlarmCount, scope.row.avgVisitAlarmCount)
								}}</span>
							</template>
						</el-table-column>
						<el-table-column prop="healthRatio" label="健康度" sortable="'custom'" :show-overflow-tooltip="true" width="140">
							<template #default="scope">
								<a>{{ scope.row.healthRatio.toFixed(2) + '%' }}</a>
								<svg-icon :icon-class="rowIcon(scope.row.healthRatio, scope.row.avgHealthRatio)" class="icon-class" />
								<span :style="rowSpanClass(scope.row.healthRatio, scope.row.avgHealthRatio)">{{
									rowRate(scope.row.healthRatio, scope.row.avgHealthRatio)
								}}</span>
							</template>
						</el-table-column>
						<template #empty> <svg-icon class-name="nodata" icon-class="nodata"></svg-icon>暂无数据~ </template>
					</el-table>
				</div>
			</el-col>
		</el-row>
	</div>
</template>

<script setup name="VisitDistribteDetail" lang="ts">
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';
import { onActivated, ref, reactive, onMounted, onBeforeUnmount, onBeforeMount } from 'vue';

import { getVisitDistribteDetail } from '@/api/bpm/home/visit_distribte_detail_api';
import { tableSort, parseTime, toDecimalFormate } from '@/utils/common';
import * as echarts from 'echarts';
// import chinaData from '/public/Echart/map/china.json';
import { getConfigKey } from '@/api/management/systemManage/systemConfig';

let route = useRoute();
let router = useRouter();

let porps = defineProps({
	width: {
		type: String,
		default: '100%',
	},
	height: {
		type: String,
		default: '800px',
	},
});

let place: anyObj = {};
let mapRef = ref(null);

// 遮罩层
let loading = ref(false);
// 查询参数
let queryParams = reactive<FormModelType>({
	currentTime: parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:00'),
});
//页面ui
let ui = reactive<anyObj>({});
//地图对象
let chart = reactive<anyObj>({
	map: null,
});
// 总条数
let total = ref(0);
let pageNum = ref(1);
let pageSize = ref(10);
let currentPage = ref(1); //初始页
//右侧grid结果集
let tableData = ref([]);
let mapData = ref<any[]>([]);
let systemName = ref('');

onBeforeMount(() => {
	let base = import.meta.env.VITE_APP_ASSETS_BASEURL;
	axios.get(`${base}/Echart/map/china.json`).then((res) => {
		console.log('res', res);
		echarts.registerMap('china', res.data);
	});
});

// resizeMixins(chart)

onMounted(() => {
	getMapConfig().then((flag: boolean) => {
		getProvinceMap(place, flag);
	});
});
onActivated(() => {
	initQuery(route.query, queryParams);
	queryVisitDistribteDetail().then(() => {
		getMapOpt(place);
	});
});

onBeforeUnmount(() => {
	if (!chart.map) {
		return;
	}
	chart.map.dispose();
	chart.map = null;
});
// 初始化参数
function initQuery(query: anyObj, form: FormModelType) {
	for (let key in query) {
		form[key] = query[key];
	}
}

/**
 * 配置地图参数
 */
function getMapOpt(p: any) {
	chart.map = echarts.init(mapRef.value!);
	chart.map.showLoading();
	chart.map.setOption({
		title: {
			show: true,
			text: systemName.value,
			left: 'center',
			textStyle: {
				color: '#fff',
				textShadowColor: '#01153b',
				textShadowBlur: 9,
				textShadowOffsetX: 3,
				textShadowOffsetY: 3,
			},
		},
		visualMap: {
			show: true,
			min: 0,
			max: 1000,
			realtime: true, //拖拽时是否更新
			orient: 'horizontal', //展现方式
			left: '35%',
			itemWidth: 10,
			itemHeight: 211,
			calculable: true, //是否展示拖拽手柄
			color: ['#04325f', '#00a4d5'],
			textStyle: {
				color: '#FFF',
			},
		},
		geo: {
			map: p,
			roam: true,
			label: {
				show: true, //显示省份标签
				textStyle: {
					color: 'rgb(255,255,255)', //省份字体颜色
				},
			},
			itemStyle: {
				borderColor: 'rgb(0,255,255)', //地图边线颜色
				borderWidth: 2, //边线宽度
				color: 'rgb(0,164,213)', //地图底色，
			},
			emphasis: {
				//对应鼠标悬停效果
				itemStyle: {
					areaColor: '#2beded',
					shadowOffsetX: 0,
					shadowOffsetY: 0,
					shadowBlur: 20,
					borderWidth: 0,
					shadowColor: 'rgba(0,0,0,0.5)',
				},
			},
		},
		series: [
			{
				type: 'scatter',
				coordinateSystem: 'geo', //对应上方配置
			},
			{
				name: 1, //浮动框的 标题
				type: 'map',
				geoIndex: 0,
				nameProperty: 'NAME',
				data: mapData.value,
			},
		],
	});
	chart.map.hideLoading();
}
/**
 * 获取地图JSON
 * @param area 区域名称&编码
 * @param isProvince 是否省份，用于区分获取不同的JSON
 */
function getProvinceMap(area: any, isProvince: boolean) {
	let base = import.meta.env.VITE_APP_ASSETS_BASEURL;
	if (isProvince) {
		axios.get(`${base}/Echart/map/json/province/${area}.json`).then((res) => {
			console.log('res', res);
			echarts.registerMap(area, res.data);
		});
	} else {
		axios.get(`${base}/Echart/map/json/city/${area}.json`).then((res) => {
			console.log('re1s', res);
			echarts.registerMap(area, res.data);
		});
	}
}

function toDecimalFormat(date: string) {
	return toDecimalFormate(date);
}
/**
 * 列表查询
 */
function queryVisitDistribteDetail() {
	loading.value = true;
	return getVisitDistribteDetail(queryParams).then((res) => {
		if (res.code === 0) {
			let list = res.data.data;
			let mapItem: any[] = [];
			list.forEach((item: anyObj) => {
				let data = { name: item.areaName, value: item.visitCount };
				mapItem.push(data);
				if (item.systemName !== null) systemName.value = item.systemName;
			});
			mapData.value = mapItem;
			tableData.value = list;
			total.value = res.data.total;
		}
		loading.value = false;
	});
}
/**
 * 列表头触发排序
 */
function sorable(column: any) {
	tableSort(queryParams, column, queryVisitDistribteDetail);
}

function rowIcon(sum1: number, sum2: number) {
	if (sum1 > sum2) return 'upicon';
	if (sum1 < sum2) return 'downiconred';
	else return 'equalicon';
}
function rowSpanClass(sum1: number, sum2: number) {
	if (sum1 > sum2) return 'color: #d9001b;';
	if (sum1 < sum2) return 'color: #04edb8;';
}
function rowRate(sum1: number, sum2: number) {
	// console.log()
	if (sum1 > sum2) return sum2 > 1 ? Math.floor(((sum1 - sum2) / sum2) * 100).toFixed(2) + '%' : sum1.toFixed(2) + '%';
	if (sum1 < sum2) return Math.floor(((sum2 - sum1) / sum2) * 100).toFixed(2) + '%';
}
/**
 * 获取系统区域配置信息
 * @param complete 回调
 */
function getMapConfig(): Promise<boolean> {
	return new Promise((resolve) => {
		getConfigKey('sys.project.map').then((res) => {
			place = res.data;
			resolve(true);
		});
	});
}
//跳转到业务查询页面
function handleRouterBusinessOverview(row: anyObj) {
	let code = row.areaCode || '';
	router.push({
		path: '/business-monitor/monitor-query/business-overview-list',
		query: {
			data: JSON.stringify({
				systemId: row.systemId,
				areaCodeList: [code],
				startTime: parseTime(queryParams.currentTime, '{y}-{m}-{d} 00:00:00'),
				endTime: parseTime(queryParams.currentTime, '{y}-{m}-{d} {h}:{i}:00'),
			}),
		},
	});
}
//跳转到告警业务查询
function handleRouterBusiDetailAlarm(row: anyObj) {
	router.push({
		path: '/business-monitor/monitor-query/business-overview-list',
		query: {
			data: JSON.stringify({
				systemId: row.systemId,
				areaCodeList: [row.areaCode],
				startTime: parseTime(queryParams.currentTime, '{y}-{m}-{d} 00:00:00'),
				endTime: parseTime(queryParams.currentTime, '{y}-{m}-{d} {h}:{i}:00'),
			}),
		},
	});
}
</script>

<style scoped>
.bg-map {
	height: 858px;
}

:deep(.el-table) {
	font-size: 12px;
}

:deep(.el-table tbody tr:last-child td) {
	border-bottom: none;
}

.icon-class {
	margin-left: 4px;
	margin-right: 4px;
	height: 14px;
	width: 10px;
}
</style>
